<template>
	<view class="container-bottom-btns">
		<view class="form">
			<view class="form-row-item">
				<view class="label">收货人</view>
				<view class="content">
					<input type="text" placeholder="请输入收货人姓名" v-model="form.realName"/>
				</view>
			</view>
			<view class="form-row-item">
				<view class="label">联系电话</view>
				<view class="content">
					<input type="tel" placeholder="请输入联系电话" maxlength="11" v-model="form.phone">
				</view>
			</view>
			<view class="form-row-item">
				<view class="label">所在地区</view>
				<view class="picker-content" @tap="$refs.region.open()">
					<view :class="{'placeholder-picker': !regionStr, 'picker-text': regionStr}">
						{{regionStr ? regionStr : '请选择省市区'}}
					</view>
					<u-icon name="arrow-down"></u-icon>
				</view>
			</view>
			<view class="form-row-item">
				<view class="label">详细地址</view>
				<view class="content">
					<input type="text" placeholder="如街道/小区/乡镇村等" v-model="form.address"/>
				</view>
			</view>
		</view>
		
		<view class="bottom-btn-wrapper">
			<SubmitBtn text="保存地址并使用" @tap="submit"></SubmitBtn>
		</view>
		
		<RegionPicker ref="region" @regionConfirm="regionConfirm"
			:provinceId="form.provinceId" :cityId="form.cityId" :areaId="form.areaId"></RegionPicker>
	</view>
</template>

<script>
	import { toast } from '../../utils/uni-api';
import { saveOrUpdateAddress, getDefaultAddress } from '@/api/user.js'
	import validate from '@/utils/validate.js'
	export default {
		data() {
			return {
				showRegionPicker: false,
				form:{
					realName: '',
					phone: '',
					provinceId: '',
					province: '',
					cityId: '',
					city: '',
					areaId: '',
					area: '',
					address: '',
				}
			};
		},
		onLoad(){
			this.getDefaultAddress()
		},
		computed:{
			regionStr(){
				return this.form.provinceId ? `${this.form.province},${this.form.city},${this.form.area}` : ''
			}
		},
		methods:{
			getDefaultAddress(){
				getDefaultAddress().then(res => {
					if(res.result){
						this.form = res.result
					}
				})
			},
			regionConfirm(e){
				this.form.provinceId = e.value[0].value
				this.form.cityId = e.value[1].value
				this.form.areaId = e.value[2].value
				this.form.province = e.value[0].label
				this.form.city = e.value[1].label
				this.form.area = e.value[2].label
			},
			submit(){
				if(!validate.isNotEmpty(this.form.realName, '收货人')) return
				if(!validate.isNotEmpty(this.form.phone, '联系电话')) return
				if(!validate.isPhone(this.form.phone, '联系电话')) return 
				if(!validate.isNotEmpty(this.form.provinceId, '所在地区')) return 
				if(!validate.isNotEmpty(this.form.address, '详细地址')) return 
				
				saveOrUpdateAddress(this.form).then(res => {
					toast('编辑成功', true)
					setTimeout(() => {
						uni.navigateBack()
					}, 800)
				})
			}
		}
	}
</script>

<style lang="scss">
	.container-bottom-btns{
		
		.form{
			margin: 0;
			padding: 0;
			
			.form-row-item{
				padding: 40rpx 0;
			}
		}
	}
</style>
